package com.haiheng.library_base.mqtt
import com.haiheng.library.log.LogUtils
import org.eclipse.paho.client.mqttv3.*
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2023/4/27 0027
 * @Version: 1.0
 */

class MqttConnection(
    private val serverUri: String,
    private val clientId: String
) : MqttCallbackExtended {

    private val mqttClient: MqttClient by lazy {
        MqttClient(serverUri, clientId, MemoryPersistence())
    }

    fun connect() {
        mqttClient.setCallback(this)

        val options = MqttConnectOptions()
        options.isAutomaticReconnect = true
        options.isCleanSession = true

        mqttClient.connect(options)
    }

    fun disconnect() {
        mqttClient.disconnect()
    }

    override fun connectComplete(reconnect: Boolean, serverURI: String) {
        // 连接完成后执行的操作
        LogUtils.e("MqttConnection connectComplete 连接完成后执行的操作")
    }

    override fun connectionLost(cause: Throwable?) {
        // 连接丢失后执行的操作
        LogUtils.e("MqttConnection connectionLost 连接丢失后执行的操作")
    }

    override fun messageArrived(topic: String?, message: MqttMessage?) {
        // 接收到消息后执行的操作
        LogUtils.e("MqttConnection messageArrived 接收到消息后执行的操作")
    }

    override fun deliveryComplete(token: IMqttDeliveryToken?) {
        // 消息传递完成后执行的操作
        LogUtils.e("MqttConnection deliveryComplete 消息传递完成后执行的操作")

    }
}
